package com.raycloud.util;

import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

/**
 * Description:
 * User: ouzhouyou@raycloud.com
 * Date: 14-4-17
 * Time: 上午10:41
 * Version: 1.0
 */
public class HttpUtil {

    /**
     * 开启302跳转的,并且跟踪下去的httpclient实例
     */
    private static CloseableHttpClient disableRedirectHttpclient = HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler()).disableRedirectHandling().build();
    /**
     * 关闭302跳转的httpclient实例
     */
    private static CloseableHttpClient defaultHttpclient = HttpClients.createDefault();
    private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
    private static CloseableHttpClient httpsClient;
    public static CloseableHttpClient getHttpClient(boolean isCloseRedirect) {
        if (isCloseRedirect) return disableRedirectHttpclient;
        return defaultHttpclient;
    }

    public static HttpGet buidHttGet(String url, String referer, String cookie) {
        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("Accept", "*/*");
        httpget.addHeader("Accept-Encoding", "gzip, deflate");
        httpget.addHeader("zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3", "");
        httpget.addHeader("Connection", "keep-alive");
        if (cookie != null) {
            httpget.addHeader("Cookie", cookie);
        }
        httpget.addHeader("Referer", referer);
        httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0");
        //超时配置
        httpget.setConfig(requestConfig);
        return httpget;
    }

    public static HttpGet buidHttGet(String url,Map<String,String> headerMap) {
        HttpGet httpget = new HttpGet(url);
        for(Map.Entry<String,String> entry : headerMap.entrySet()) {
            httpget.addHeader(entry.getKey(),entry.getValue());
        }
        httpget.setConfig(requestConfig);
        return httpget;
    }



    public static String getContent(String url,Map<String, String> headerMap){
        CloseableHttpClient httpclient = HttpUtil.getHttpClient(false);
        HttpGet httpget = HttpUtil.buidHttGet(url, headerMap);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
            return EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
